<script>
import MarkdownEditor from '@/components/MarkdownEditor.vue'

export default {
  name: 'BianJi1',
  components: { MarkdownEditor },
  props: ['yuanshuju'],
  data () {
    return {
      jinyong: false,
      yuanshuju1: '',
      fileList: [],
      ruleForm: {
        title: '',
        fenlei: '',
        postdate: '',
        content: '',
        imgurl: '',
        zishu: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 5, max: 32, message: '长度在 5 到 32 个字符', trigger: 'blur' }
        ],
        fenlei: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ],
        postdate: [
          { type: 'date', required: true, message: '请选择时间日期', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请填写正文', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.ruleForm.id) {
            // console.log(this.ruleForm)
            const xiangying = this.$axios.put(`houtai/adminlist/${this.ruleForm.id}/`, JSON.stringify(this.ruleForm), { headers: { 'Content-Type': 'application/json' } })
            if (xiangying) {
              location.reload()
            }
          } else {
            // console.log(this.ruleForm)
            const reponse = this.$axios.post('houtai/adminlist/', JSON.stringify(this.ruleForm), { headers: { 'Content-Type': 'application/json' } })
            if (reponse) {
              location.reload()
            }
          }
        } else {
          alert('error submit!!')
          return false
        }
      })
    },
    tjzishu (value) {
      this.ruleForm.zishu = value.replace(/\s/g, '').length // 统计字数
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    validate1 () {
      this.$refs.ruleForm.validateField('content')
    },
    async upload (param) {
      const file = param.file
      // console.log(file)
      if (file) {
        const formData = new FormData()
        formData.append('image', file)
        // const img = formData.get('image')
        try {
          // console.dir(formData)
          const response = await this.$axios.post('/houtai/uploadimg/', formData)
          // console.log(response)
          if (response.url) {
            // 获取编辑器实例
            // console.log(response.url)
            this.ruleForm.imgurl = response.url
            // console.log(this.ruleForm.imgurl)
          } else {
            alert('服务器未返回图片 URL')
          }
        } catch (error) {
          console.error('图片上传失败:', error)
          alert('图片上传失败，请稍后重试！')
        }
      }
    }
  },
  mounted () {
  },
  watch: {
    async yuanshuju () {
      if (this.yuanshuju) {
        this.yuanshuju1 = await this.$axios.get(`houtai/adminlist/${this.yuanshuju}/`)
        // console.log(this.yuanshuju1)
        this.ruleForm = this.yuanshuju1
        // console.log(this.ruleForm)
        this.jinyong = true
      }
    }
  }
}
</script>

<template>
  <div class="bianji">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"
             style="width: 70%;margin: 0 auto;">
      <el-form-item label="标题" prop="title">
        <el-input v-model="ruleForm.title"></el-input>
      </el-form-item>
      <el-form-item label="分类" prop="fenlei">
        <el-select v-model="ruleForm.fenlei" placeholder="请选择分类">
          <el-option label="Django" value="1"></el-option>
          <el-option label="Vue" value="2"></el-option>
          <el-option label="Ajax" value="3"></el-option>
          <el-option label="随记" value="4"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发布时间" required>
        <el-col :span="11">
          <el-form-item prop="postdate">
            <el-date-picker
              v-model="ruleForm.postdate"
              type="datetime"
              placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="上传图片">
        <el-upload
          :disabled="jinyong"
          class="upload-demo"
          action=""
          :http-request="upload"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          list-type="picture">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="正文" prop="desc">
          <markdown-editor v-model="ruleForm.content" @input="tjzishu"></markdown-editor>
      </el-form-item>
      <el-form-item prop="content">
        <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
      <!--      <div v-html="ruleForm.content"></div>-->
      <!--      <div>{{ ruleForm }}</div>-->
    </el-form>

  </div>
</template>

<style scoped lang="scss">
.binaji {
  display: flex;
  min-height: 1000px;
  background: #2c3e50;
}
</style>
